import JSZip from 'jszip';
import { saveAs } from 'file-saver';

/**
 * zip:zip对象
 *  loadAsync 加载File文件
 *  generateAsync 生成指定类型
 *  file 添加或者获取file文件
 *  remove
 *  filter
 *  forEach
 * zipFileObj:zip对象中的file对象
 *  async 生成指定类型
 *  xxx 文件信息
 *
 * zip支持交互的文件类型
 * interface InputByType {
 *     base64: string;
 *     string: string;
 *     text: string;
 *     binarystring: string;
 *     array: number[];
 *     uint8array: Uint8Array;
 *     arraybuffer: ArrayBuffer;
 *     blob: Blob;
 *     stream: NodeJS.ReadableStream;
 * }
 */
interface InputByType {
  base64: string;
  string: string;
  text: string;
  binarystring: string;
  array: number[];
  uint8array: Uint8Array;
  arraybuffer: ArrayBuffer;
  blob: Blob;
  stream: NodeJS.ReadableStream;
}
export type ZipFileOptions<T extends keyof InputByType = keyof InputByType> = {
  path: string;
  data: InputByType[T] | Promise<InputByType[T]>;
};
// 解析压缩包File
export async function getZipFile(file: File) {
  const jsFile = new JSZip();
  const { files } = await jsFile.loadAsync(file);
  const fileNames = Object.keys(files);
  return [fileNames, files] as [string[], Record<string, JSZip.JSZipObject>];
}

// 生成压缩包文件
export async function createZipFile(fileOptions: ZipFileOptions[], fileName = '未命名.zip') {
  const zip = new JSZip();
  fileOptions.forEach((fileOpt) => {
    zip.file(fileOpt.path, fileOpt.data);
  });
  const blob = await zip.generateAsync({ type: 'blob' });
  saveAs(blob, fileName);
}

/**
 * pdf相关操作
 */
